package cn.whut.glab.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.whut.glab.service.UserService;

/**
 * Servlet implementation class FunctionServlet
 */
public class MainServlet extends HttpServlet {
	UserService service=new UserService();

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		HttpSession session=request.getSession();
		try {
			if(password.equals(service.getPassword(userName))){//登录成功时
				//把用户名加入到cookie中,中文采用unicode编码，英文采用ASCII编码，当cookie保存中文时需要对中文进行编码，从cookie中取出内容时，需要进行解码
				Cookie cookies=new Cookie("uname",URLEncoder.encode(userName,"utf-8"));
				cookies.setMaxAge(60*60*24);
				response.addCookie(cookies);			
				session.setAttribute("userName", userName);
				response.sendRedirect("/GlabManager/main.jsp");
			}else{
				request.setAttribute("msg", "您输入的密码有误");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
